﻿using System;
using System.Collections.Generic;
using System.Reflection;

namespace HouseOfTheFuture
{
    public class PluginManager
    {
        public struct Plugin
        {
            public string AssemblyPath;
            public string TypeName;
        }
        public static List<Plugin> LoadPlugins(string path, string strInterface)
        {
            List<Plugin> plugins = new List<Plugin>();
            foreach (string myFile in System.IO.Directory.GetFiles(path, "*.dll"))
            {
                Assembly dll = Assembly.LoadFrom(myFile);
                foreach (Type type in dll.GetTypes())
                {
                    if (type.IsPublic && (type.Attributes != TypeAttributes.Abstract))
                    {
                        if (type.GetInterface(strInterface, true) != null)
                        {
                            Plugin plugin = new Plugin();
                            plugin.AssemblyPath = dll.Location;
                            plugin.TypeName = type.FullName;
                            plugins.Add(plugin);
                        }
                    }
                }

                dll = null;
            }
            return plugins;
        }

        public static List<Plugin> LoadPlugins(string path, string strInterface, string strInterface2)
        {
            List<Plugin> plugins = new List<Plugin>();
            foreach (string myFile in System.IO.Directory.GetFiles(path, "*dll"))
            {
                Assembly dll = Assembly.LoadFrom(myFile);
                foreach (Type type in dll.GetTypes())
                {
                    if (type.IsPublic && (type.Attributes != TypeAttributes.Abstract))
                    {
                        if (type.GetInterface(strInterface, true) != null || type.GetInterface(strInterface2, true) != null)
                        {
                            Plugin plugin = new Plugin();
                            plugin.AssemblyPath = dll.Location;
                            plugin.TypeName = type.FullName;
                            plugins.Add(plugin);
                        }
                    }
                }

                dll = null;
            }
            return plugins;
        }

        public static object CreateInstance(Plugin plugin)
        {
            Assembly dll = Assembly.LoadFrom(plugin.AssemblyPath);
            return dll.CreateInstance(plugin.TypeName);
        }
    }
}
